<template>
  <div class="result">
    <div class="container">
      <div class="result-header">
        <h1>🎉 答题完成</h1>
      </div>
      
      <div v-if="loading" class="loading">
        <p>正在加载结果...</p>
      </div>
      
      <div v-else-if="error" class="error">
        <p>{{ error }}</p>
        <button @click="$router.push('/')" class="btn">返回首页</button>
      </div>
      
      <div v-else class="result-content">
        <!-- 得分显示 -->
        <div class="score-display">
          <div class="score-circle">
            <div class="score-number">{{ result.score }}</div>
            <div class="score-label">分</div>
          </div>
          <h2>{{ studentName }}，你的得分是：{{ result.score }}分</h2>
          <div class="score-stats">
            <span class="stat-item">
              <span class="stat-label">正确题数：</span>
              <span class="stat-value correct">{{ correctCount }}</span>
            </span>
            <span class="stat-item">
              <span class="stat-label">错误题数：</span>
              <span class="stat-value incorrect">{{ incorrectCount }}</span>
            </span>
            <span class="stat-item">
              <span class="stat-label">正确率：</span>
              <span class="stat-value">{{ accuracyRate }}%</span>
            </span>
          </div>
        </div>
        
        <!-- 可视化图表 -->
        <div class="charts-section">
          <h3>📊 可视化分析</h3>
          <div class="charts-container">
            <div class="chart-item">
              <h4>答题正确率分布</h4>
              <div class="chart-wrapper">
                <canvas ref="pieChart"></canvas>
              </div>
            </div>
            <div class="chart-item">
              <h4>各题答题情况</h4>
              <div class="chart-wrapper">
                <canvas ref="barChart"></canvas>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 题目详情 -->
        <div class="questions-review">
          <h3>📋 答题详情</h3>
          <div 
            v-for="(question, index) in result.full_results" 
            :key="index"
            class="question-review-card"
            :class="{ 'correct': question.isCorrect, 'incorrect': !question.isCorrect }"
          >
            <div class="question-header">
              <span class="question-number">第 {{ index + 1 }} 题</span>
              <span class="question-status" :class="question.isCorrect ? 'correct' : 'incorrect'">
                {{ question.isCorrect ? '✓ 正确' : '✗ 错误' }}
              </span>
            </div>
            
            <div class="question-content">
              <div class="question-title">{{ question.questionContent }}</div>
              
              <div class="answer-comparison">
                <div class="answer-row">
                  <span class="answer-label">你的答案：</span>
                  <span class="answer-value" :class="question.isCorrect ? 'correct' : 'incorrect'">
                    {{ question.yourAnswer || '未作答' }}
                  </span>
                </div>
                <div class="answer-row">
                  <span class="answer-label">正确答案：</span>
                  <span class="answer-value correct">{{ question.correctAnswer }}</span>
                </div>
              </div>
              
              <div class="knowledge-point">
                <strong>💡 知识点解析：</strong>
                {{ question.knowledgePoint }}
              </div>
              
              <!-- 答案解释 -->
              <div v-if="question.explanation" class="explanation">
                <strong>📖 答案解释：</strong>
                {{ question.explanation }}
              </div>
              
              <!-- 错题分析 -->
              <div v-if="!question.isCorrect && question.wrongAnalysis" class="wrong-analysis">
                <strong>🔍 错题分析：</strong>
                {{ question.wrongAnalysis }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="actions">
          <button @click="$router.push('/')" class="btn secondary-btn">
            🏠 返回首页
          </button>
          <button @click="retakeQuiz" class="btn primary-btn">
            🔄 重新答题
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js'

// 注册Chart.js组件
Chart.register(...registerables)

export default {
  name: 'Result',
  data() {
    return {
      result: null,
      studentName: '',
      loading: true,
      error: null,
      pieChart: null,
      barChart: null
    }
  },
  computed: {
    correctCount() {
      if (!this.result || !this.result.full_results) return 0
      return this.result.full_results.filter(q => q.isCorrect).length
    },
    incorrectCount() {
      if (!this.result || !this.result.full_results) return 0
      return this.result.full_results.filter(q => !q.isCorrect).length
    },
    totalQuestions() {
      if (!this.result || !this.result.full_results) return 0
      return this.result.full_results.length
    },
    accuracyRate() {
      if (this.totalQuestions === 0) return 0
      return Math.round((this.correctCount / this.totalQuestions) * 100)
    }
  },
  created() {
    this.loadResult()
  },
  methods: {
    loadResult() {
      try {
        // 从sessionStorage获取结果
        const resultData = sessionStorage.getItem('quizResult')
        this.studentName = sessionStorage.getItem('studentName') || '同学'
        
        if (!resultData) {
          this.error = '未找到答题结果，请重新答题'
          this.loading = false
          return
        }
        
        this.result = JSON.parse(resultData)
        this.loading = false
        
        // 等待DOM更新后初始化图表
        this.$nextTick(() => {
          this.initCharts()
        })
        
      } catch (error) {
        console.error('加载结果失败:', error)
        this.error = '加载结果失败'
        this.loading = false
      }
    },
    
    retakeQuiz() {
      // 清除之前的结果
      sessionStorage.removeItem('quizResult')
      // 跳转到答题页面
      this.$router.push('/quiz')
    },
    
    initCharts() {
      this.initPieChart()
      this.initBarChart()
    },
    
    initPieChart() {
      const ctx = this.$refs.pieChart.getContext('2d')
      
      if (this.pieChart) {
        this.pieChart.destroy()
      }
      
      this.pieChart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: ['正确', '错误'],
          datasets: [{
            data: [this.correctCount, this.incorrectCount],
            backgroundColor: [
              '#28a745',
              '#dc3545'
            ],
            borderWidth: 2,
            borderColor: '#fff'
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          layout: {
            padding: {
              top: 10,
              bottom: 10,
              left: 10,
              right: 10
            }
          },
          plugins: {
            legend: {
              position: 'bottom',
              labels: {
                padding: 15,
                font: {
                  size: 12
                },
                boxWidth: 12
              }
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  const label = context.label || ''
                  const value = context.parsed
                  const total = context.dataset.data.reduce((a, b) => a + b, 0)
                  const percentage = Math.round((value / total) * 100)
                  return `${label}: ${value}题 (${percentage}%)`
                }
              }
            }
          }
        }
      })
    },
    
    initBarChart() {
      const ctx = this.$refs.barChart.getContext('2d')
      
      if (this.barChart) {
        this.barChart.destroy()
      }
      
      const questionNumbers = this.result.full_results.map((_, index) => `第${index + 1}题`)
      const questionResults = this.result.full_results.map(q => q.isCorrect ? 1 : 0)
      
      this.barChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: questionNumbers,
          datasets: [{
            label: '答题结果',
            data: questionResults,
            backgroundColor: questionResults.map(result => 
              result === 1 ? '#28a745' : '#dc3545'
            ),
            borderColor: questionResults.map(result => 
              result === 1 ? '#1e7e34' : '#c82333'
            ),
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          layout: {
            padding: {
              top: 10,
              bottom: 10,
              left: 10,
              right: 10
            }
          },
          scales: {
            y: {
              beginAtZero: true,
              max: 1,
              ticks: {
                stepSize: 1,
                callback: function(value) {
                  return value === 1 ? '正确' : '错误'
                },
                font: {
                  size: 11
                }
              }
            },
            x: {
              ticks: {
                maxRotation: 45,
                minRotation: 0,
                font: {
                  size: 10
                },
                maxTicksLimit: 10
              }
            }
          },
          plugins: {
            legend: {
              display: false
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  return context.parsed.y === 1 ? '正确' : '错误'
                }
              }
            }
          }
        }
      })
    }
  },
  
  beforeDestroy() {
    if (this.pieChart) {
      this.pieChart.destroy()
    }
    if (this.barChart) {
      this.barChart.destroy()
    }
  }
}
</script>

<style scoped>
.result {
  min-height: 100vh;
  padding: 20px;
}

.result-header {
  text-align: center;
  margin-bottom: 30px;
}

.result-header h1 {
  color: #333;
  font-size: 2.5em;
}

.loading, .error {
  text-align: center;
  padding: 40px;
  color: #666;
}

.score-display {
  text-align: center;
  margin-bottom: 40px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea20, #764ba220);
  border-radius: 15px;
  border: 2px solid #667eea30;
}

.score-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(45deg, #667eea, #764ba2);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.score-number {
  font-size: 2.5em;
  font-weight: bold;
  color: white;
  line-height: 1;
}

.score-label {
  font-size: 1em;
  color: white;
  opacity: 0.9;
}

.score-display h2 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.8em;
}

.score-stats {
  display: flex;
  justify-content: center;
  gap: 30px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
}

.stat-value.correct {
  color: #28a745;
}

.stat-value.incorrect {
  color: #dc3545;
}

.questions-review {
  margin-bottom: 40px;
}

.questions-review h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.5em;
}

.question-review-card {
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  border: 2px solid;
  transition: all 0.3s ease;
}

.question-review-card.correct {
  border-color: #28a745;
  background-color: #d4edda;
}

.question-review-card.incorrect {
  border-color: #dc3545;
  background-color: #f8d7da;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.question-number {
  background: #6c757d;
  color: white;
  padding: 5px 12px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: bold;
}

.question-status {
  padding: 5px 12px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: bold;
}

.question-status.correct {
  background-color: #28a745;
  color: white;
}

.question-status.incorrect {
  background-color: #dc3545;
  color: white;
}

.question-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.answer-comparison {
  margin-bottom: 15px;
}

.answer-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.answer-label {
  font-weight: bold;
  min-width: 100px;
  color: #555;
}

.answer-value {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: bold;
}

.answer-value.correct {
  background-color: #28a745;
  color: white;
}

.answer-value.incorrect {
  background-color: #dc3545;
  color: white;
}

.knowledge-point {
  background: #e3f2fd;
  border-left: 4px solid #2196f3;
  padding: 12px;
  border-radius: 0 5px 5px 0;
  font-size: 14px;
  line-height: 1.5;
}

.explanation {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #28a745;
  margin-top: 15px;
  font-size: 14px;
  line-height: 1.5;
}

.wrong-analysis {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin-top: 15px;
  font-size: 14px;
  line-height: 1.5;
  color: #856404;
}

.charts-section {
  margin-bottom: 40px;
  padding: 30px;
  background: #f8f9fa;
  border-radius: 15px;
  border: 1px solid #e9ecef;
}

.charts-section h3 {
  color: #333;
  margin-bottom: 25px;
  font-size: 1.5em;
  text-align: center;
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  align-items: start;
}

.chart-item {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  text-align: center;
  overflow: hidden;
}

.chart-item h4 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.2em;
}

.chart-wrapper {
  position: relative;
  height: 300px;
  width: 100%;
  max-width: 100%;
  overflow: hidden;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 30px 0;
}

.secondary-btn {
  background: #6c757d;
}

.secondary-btn:hover {
  background: #545b62;
}

.primary-btn {
  background: linear-gradient(45deg, #667eea, #764ba2);
}

@media (max-width: 768px) {
  .score-stats {
    gap: 15px;
    flex-direction: column;
  }
  
  .charts-container {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .chart-wrapper {
    height: 250px;
    min-height: 200px;
  }
  
  .chart-item {
    padding: 15px;
    margin: 0 auto;
    max-width: 100%;
  }
  
  .chart-item h4 {
    font-size: 1.1em;
    margin-bottom: 15px;
  }
  
  .charts-section {
    padding: 15px;
    margin: 0 -10px;
  }
  
  .charts-section h3 {
    font-size: 1.3em;
  }
  
  .actions {
    flex-direction: column;
    align-items: center;
  }
  
  .actions .btn {
    width: 200px;
  }
  
  .question-review-card {
    padding: 15px;
    margin-bottom: 15px;
  }
  
  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .answer-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .answer-label {
     min-width: auto;
   }
 }

@media (max-width: 480px) {
  .container {
    padding: 15px;
    margin-top: 20px;
  }
  
  .result {
    padding: 10px;
  }
  
  .score-display {
    padding: 20px;
  }
  
  .score-circle {
    width: 100px;
    height: 100px;
  }
  
  .score-number {
    font-size: 2em;
  }
  
  .score-display h2 {
    font-size: 1.5em;
  }
  
  .charts-section {
    padding: 10px;
    margin: 0 -5px;
  }
  
  .chart-wrapper {
    height: 200px;
  }
  
  .chart-item {
    padding: 10px;
  }
  
  .question-review-card {
    padding: 12px;
  }
  
  .question-title {
    font-size: 14px;
  }
  
  .knowledge-point,
  .explanation,
  .wrong-analysis {
    padding: 10px;
    font-size: 13px;
  }
}
</style>